<template>
  <el-container>
    <!-- 侧边栏 -->
    <el-aside class="home-aside" width="250px">
      <!-- logo -->
      <div class="home-logo-div" v-if="!isOwner">
        <router-link to="/customer/home">
          <el-image
            class="home-logo"
            src="../src/assets/logo_trans.png"
            fit="contain"
          ></el-image
        ></router-link>
      </div>
      <div class="home-logo-div" v-if="isOwner">
        <router-link to="/owner/home">
          <el-image
            class="home-logo"
            src="../src/assets/logo_trans.png"
            fit="contain"
          ></el-image
        ></router-link>
      </div>
      <!-- 折叠icon -->
      <el-icon
        class="toggle-button"
        v-model="isCollapse"
        @click="toggleCollapse"
        size="20px"
      >
        <Fold v-if="!isCollapse" />
        <Expand v-if="isCollapse" />
      </el-icon>
      <!-- 侧边栏菜单 -->
      <el-menu
        class="home-menu-vertical"
        :collapse="isCollapse"
        :default-active="$route.path"
        router
        active-text-color="#E3A566"
        v-if="!isOwner"
      >
        <el-menu-item index="/customer/food">
          <el-icon><Search /></el-icon>
          <span slot="title">菜品列表</span>
        </el-menu-item>
        <el-menu-item index="/customer/recommend">
          <el-icon><MagicStick /></el-icon>
          <span slot="title">猜你想吃</span>
        </el-menu-item>
        <el-menu-item index="/customer/order">
          <el-icon><Wallet /></el-icon>
          <span slot="title">我的订单</span>
        </el-menu-item>
        <el-menu-item index="/customer/account">
          <el-icon><User /></el-icon>
          <span slot="title">我的账号</span>
        </el-menu-item>
      </el-menu>
      <el-menu
        class="home-menu-vertical"
        :collapse="isCollapse"
        :default-active="$route.path"
        router
        v-if="isOwner"
      >
        <el-menu-item index="/owner/food">
          <el-icon>
            <Edit />
          </el-icon>
          <span slot="title">菜品管理</span>
        </el-menu-item>
        <el-menu-item index="/owner/order">
          <el-icon>
            <Bell />
          </el-icon>
          <span slot="title">订单管理</span>
        </el-menu-item>
        <el-menu-item index="/owner/account">
          <el-icon>
            <User />
          </el-icon>
          <span slot="title">我的账号</span>
        </el-menu-item>
      </el-menu>
      <el-image src="../src/assets/plate.png" class="plate-div"></el-image>
    </el-aside>

    <el-container>
      <!-- 头部 -->
      <el-header class="order-header" height="80px">
        <div class="ball"></div>
        <div class="food-line"></div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/customer/home' }" v-if="!isOwner">
            主页
          </el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/owner/home' }" v-if="isOwner">
            主页
          </el-breadcrumb-item>
          <el-breadcrumb-item>订单列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索&筛选 -->
        <el-row class="food-search-row" :gutter="10">
          <el-col :span="4"
            ><el-input
              v-model="commentKeyword"
              prefix-icon="Search"
              placeholder="评论关键字"
              @input="handleSearch"
          /></el-col>

          <el-col :span="4" :offset="0">
            排序：
            <el-select
              class="food-sort-basis-select"
              v-model="selectedSortBasis"
              placeholder=" "
              @change="handleSearch"
            >
              <el-option
                v-for="item in sortBasisOptions"
                :key="item.value"
                :label="item.label"
                :value="item.query"
              />
            </el-select>
          </el-col>
          <el-col :span="3" :offset="0">
            <el-button class="food-sort-button" @click="changeAsc"
              ><el-icon class="food-sort-icon" style="color: #e3a566"
                ><Sort /></el-icon></el-button
            ><span>&nbsp{{ ascText }}</span>
          </el-col>
          <el-col :span="2" :offset="0">
            <el-button
              type="info"
              @click="clear"
              class="food-clear-button"
              :disabled="isDisabled"
              >清空筛选</el-button
            >
          </el-col>
        </el-row>
      </el-header>

      <!-- 主体 -->
      <el-main>
        <el-tabs
          v-if="isTabShow"
          tab-position="top"
          class="food-tabs"
          @tab-click="getOrderByTab"
          v-model="activeName"
        >
          <el-scrollbar height="440px">
            <el-tab-pane
              v-for="option in stateOptions"
              :key="option.name"
              :label="option.label"
              :name="option.name"
            >
              <div v-if="orderList.length === 0">
                <el-image
                  src="../src/assets/emptyOrder.png"
                  style="width: 100px"
                ></el-image>
                <div>暂无</div>
              </div>
              <el-row v-if="orderList.length !== 0">
                <el-col v-for="orderEntity in orderList" :key="orderEntity.id" :span="24">
                  <!-- 待接单/制作中 -->
                  <el-card
                    class="order-card"
                    @click="gotoOrderDetail(orderEntity.id)"
                    v-if="activeName === 'orderPlaced' || activeName === 'orderAccepted'"
                  >
                    <el-descriptions :column="2" class="orderdetail-des">
                      <el-descriptions-item label="下单时间">{{
                        orderEntity.orderTime
                      }}</el-descriptions-item>
                      <el-descriptions-item label="收货地址">{{
                        orderEntity.addressName
                      }}</el-descriptions-item>
                      <el-descriptions-item
                        label="收货人"
                        v-if="orderEntity.addressName !== '堂食'"
                        >{{ orderEntity.recipientName }}</el-descriptions-item
                      >
                      <el-descriptions-item
                        label="电话号码"
                        v-if="orderEntity.addressName !== '堂食'"
                        >{{ orderEntity.phoneNumber }}</el-descriptions-item
                      >
                    </el-descriptions>
                    <el-divider content-position="left">菜品信息</el-divider>
                    <!-- 菜品列表 -->
                    <el-row :gutter="10">
                      <el-col
                        v-for="foodEntity in orderEntity.foodJudgementList"
                        :key="foodEntity.foodName"
                        :span="6"
                      >
                        <!-- 左侧图像 -->
                        <el-image class="order-image" :src="foodEntity.photo" fit="cover">
                        </el-image>
                        <!-- 右侧信息 -->
                        <div class="order-food-title">
                          <span>{{ foodEntity.foodName }}</span
                          ><br />
                          <div style="float: left">
                            ×&nbsp{{ foodEntity.foodNumber }}&nbsp
                          </div>
                          <div style="float: right">￥{{ foodEntity.foodPrice }}</div>
                        </div>
                      </el-col>
                    </el-row>
                    <div>总价：￥ {{ orderEntity.price }}</div>
                    <div class="order-o-operation-div" v-if="isOwner">
                      <el-button
                        type="success"
                        @click="accept(orderEntity)"
                        v-if="activeName === 'orderPlaced'"
                        >接单</el-button
                      >
                      <el-button
                        type="warning"
                        @click="reject(orderEntity)"
                        v-if="activeName === 'orderPlaced'"
                        >拒单</el-button
                      >
                      <el-button
                        type="success"
                        @click="finish(orderEntity)"
                        v-if="activeName === 'orderAccepted'"
                        >完成</el-button
                      >
                    </div>
                  </el-card>

                  <!-- 已完成 -->
                  <el-card
                    class="order-card"
                    @click="gotoOrderDetail(orderEntity.id)"
                    v-if="activeName === 'orderFinished'"
                  >
                    <!-- 左侧图像 -->
                    <el-image class="order-image" :src="orderEntity.photo" fit="cover">
                    </el-image>
                    <!-- 右侧信息 -->
                    <div class="order-time">
                      <div>下单时间： {{ orderEntity.orderTime }}</div>
                      <div>
                        我的评论：<span class="order-comment">
                          {{ orderEntity.comment }}</span
                        >
                      </div>
                    </div>
                    <div class="order-rate-div">
                      <span>
                        口味：
                        <el-rate
                          v-model="orderEntity.tasteScore"
                          disabled
                          show-score
                          text-color="#ff9900"
                          score-template="{value} 分" /></span
                      ><br />
                      <span>
                        服务：
                        <el-rate
                          v-model="orderEntity.serviceScore"
                          disabled
                          show-score
                          text-color="#ff9900"
                          score-template="{value} 分"
                      /></span>
                      <br />
                      <span>
                        环境：
                        <el-rate
                          v-model="orderEntity.environmentScore"
                          disabled
                          show-score
                          text-color="#ff9900"
                          score-template="{value} 分"
                      /></span></div
                  ></el-card>
                  <!-- 已拒绝 -->
                  <el-card
                    class="order-card"
                    @click="gotoOrderDetail(orderEntity.id)"
                    v-if="activeName === 'orderRejected'"
                  >
                    <!-- 左侧图像 -->
                    <el-image class="order-image" :src="orderEntity.photo" fit="cover">
                    </el-image>
                    <!-- 右侧信息 -->
                    <div class="order-time">
                      <div>下单时间： {{ orderEntity.orderTime }}</div>
                      <div>拒单时间： {{ orderEntity.orderRectime }}</div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-scrollbar>
          <div class="pagination">
            <el-pagination
              background
              small
              :current-page="pagination.currentPage"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </el-tabs>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      isCollapse: false, //是否折叠侧边栏
      orderList: [],
      orderDtoEntity: [],
      stateOptions: [
        {
          name: "orderPlaced",
          label: "待接单",
        },
        {
          name: "orderAccepted",
          label: "制作中",
        },
        {
          name: "orderFinished",
          label: "已完成",
        },
        {
          name: "orderRejected",
          label: "已拒绝",
        },
      ],
      commentKeyword: "",
      selectedSortBasis: "",
      sortBasisOptions: [
        {
          value: "Option1",
          label: "按口味",
          query: "tasteScore",
        },
        {
          value: "Option2",
          label: "按服务",
          query: "serviceScore",
        },
        {
          value: "Option3",
          label: "按环境",
          query: "environmentScore",
        },
      ],
      isAsc: true,
      ascText: "由高到低",
      account: {},
      pagination: {
        currentPage: 1, // 起始页
        pageSize: 3, // 每页的数据
        totalCount: 0, // 总数据
      },
      isOwner: false,
      isTabShow: true,
      activeName: "orderPlaced",
      isDisabled: true,
    };
  },
  computed: {
    ...mapState({
      foodInCart: (state) => state.foodInCart,
    }),
  },
  created() {
    //进入界面时，显示用户的订单信息
    this.account = JSON.parse(this.$store.state.account);
    this.isOwner = this.account.role === "owner" ? true : false;
    this.getOrderByTab({ index: 0 }); // 默认获取待接单订单
  },
  methods: {
    getMoreData(state) {
      let _this = this;
      for (let i = 0; i < _this.orderList.length; i++) {
        _this.orderList[i].photo = "http://localhost:8080" + _this.orderList[i].photo;
        //对于已完成的订单，未评论时显示信息
        if (state == "orderFinished" && _this.orderList[i].comment === null) {
          _this.orderList[i].comment = "暂未评论  去评论 >> ";
        }
        //对于已下单和制作中的订单，显示菜品信息
        if (state == "orderPlaced" || state == "orderAccepted") {
          //展示菜品信息
          let url2 = "/orders/detail/" + _this.orderList[i].id + "/" + this.account.id;
          this.$http.get(url2).then(function (response) {
            //设置地址，堂食的地址也可以这样获取
            _this.orderList[i].addressName = response.data.address.address;
            _this.orderList[i].recipientName = response.data.address.recipientName;
            _this.orderList[i].phoneNumber = response.data.address.phoneNumber;
            //设置订单的用户id
            _this.orderList[i].userID = response.data.user.id;
            //获取食品信息，包括修改图像url和设置
            _this.orderList[i].foodJudgementList = response.data.foodJudgementList;
            console.log(
              "_this.orderList[i].foodJudgementList = ",
              _this.orderList[i].foodJudgementList
            );
            let len1 = _this.orderList[i].foodJudgementList.length;
            for (let j = 0; j < len1; j++) {
              _this.orderList[i].foodJudgementList[j].photo =
                "http://localhost:8080" +
                _this.orderList[i].foodJudgementList[j].food.photo;
              _this.orderList[i].foodJudgementList[j].foodName =
                _this.orderList[i].foodJudgementList[j].food.foodName;
              _this.orderList[i].foodJudgementList[j].foodPrice =
                (_this.orderList[i].foodJudgementList[j].food.price *
                  10 *
                  _this.orderList[i].foodJudgementList[j].foodNumber) /
                10;
              _this.orderList[i].foodJudgementList[j].foodID =
                _this.orderList[i].foodJudgementList[j].food.id;
            }
          });
        }
      }
    },
    getOrderPagination(state, currentPage, pageSize, condition = null) {
      let _this = this;
      let url =
        "/orders?userID=" +
        this.account.id +
        "&&state=" +
        state +
        "&&pageNum=" +
        currentPage +
        "&&pageSize=" +
        pageSize;
      if (condition !== null && condition !== "") {
        url += condition;
        console.log("search: condition = ", condition);
      }
      _this.$http.get(url).then(function (response) {
        _this.orderList = response.data.records;
        _this.getMoreData(state);
        _this.updatePagination(_this.pagination, response.data);
      });
    },
    getOrderByTab(item) {
      let _this = this;
      // console.log("item.index = ", item.index); // 0/1/2/3
      console.log("state = ", _this.stateOptions[item.index].name);
      _this.getOrderPagination(_this.stateOptions[item.index].name, 1, 3);
    },
    // 切换侧边栏的折叠与展开
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    changeAsc() {
      this.isAsc = !this.isAsc;
      if (this.isAsc) {
        this.ascText = "由低到高";
      } else {
        this.ascText = "由高到低";
      }
      this.handleSearch();
    },
    openCart() {
      this.drawer = !this.drawer;
    },
    // 查看订单详情
    gotoOrderDetail(orderID) {
      let _this = this;
      if (_this.isOwner) {
        _this.$router.push({
          path: "/owner/orderdetail",
          state: {
            orderID: orderID,
            lastpage: "/owner/order",
          },
        });
      } else {
        _this.$router.push({
          path: "/customer/orderdetail",
          state: {
            orderID: orderID,
            lastpage: "/customer/order",
          },
        });
      }
    },
    handleSearch() {
      let _this = this;
      _this.isDisabled = false;
      let state = "orderFinished";
      _this.activeName = state;
      let condition = "";

      //根据关键字搜索
      if (this.commentKeyword !== "") {
        condition = condition + "&&comment=" + this.commentKeyword;
      }
      if (this.selectedSortBasis === "") {
        this.selectedSortBasis = "tasteScore";
      }
      condition = condition + "&&orderField=" + this.selectedSortBasis;
      if (this.isAsc) {
        condition = condition + "&&orderType=ASC";
      } else {
        condition = condition + "&&orderType=DESC";
      }

      _this.getOrderPagination(state, 1, 10, condition);
    },
    clear() {
      console.log("清空");
      this.commentKeyword = "";
      this.selectedSortBasis = "";
      this.isAsc = true;
      this.ascText = "由高到低";
      this.isDisabled = true;
      this.getOrderByTab({ index: 2 }); // 获取已完成订单
    },
    accept(orderEntity) {
      orderEntity.orderRectime = new Date().valueOf();
      let _this = this;
      console.log(orderEntity);
      this.$http.put("/orders/state", orderEntity).then(function (response) {
        _this.$message({
          message: "成功接单！",
          type: "success",
        });
        //将订单加到制作中队列
        const index = _this.orderNotAccepted.findIndex(
          (option) => option.id === orderEntity.id
        );
        //转换时间的格式
        orderDtoEntity.orderRectime = _this.getDate(orderDtoEntity.orderRectime);
        _this.orderNotAccepted.splice(index, 1);
        _this.orderAccepted.push(orderEntity);
      });
    }, //获取时间表示的格式
    getDate(n) {
      let now = new Date(n),
        y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate();
      return (
        y +
        "-" +
        (m < 10 ? "0" + m : m) +
        "-" +
        (d < 10 ? "0" + d : d) +
        " " +
        now.toTimeString().substr(0, 8)
      );
    },
    reject(orderEntity) {
      orderEntity.hasRejected = 1;
      orderEntity.orderRectime = new Date().valueOf();
      let _this = this;
      console.log(orderEntity);
      this.$http.put("/orders/state", orderEntity).then(function (response) {
        _this.$message({
          message: "成功拒单！",
          type: "success",
        });
        //将订单加到已拒绝队列
        const index = _this.orderNotAccepted.findIndex(
          (option) => option.id === orderEntity.id
        );
        //转换时间的格式
        orderDtoEntity.orderRectime = _this.getDate(orderDtoEntity.orderRectime);
        _this.orderNotAccepted.splice(index, 1);
        _this.orderRejected.push(orderEntity);
      });
    },
    finish(orderEntity) {
      orderEntity.orderFinishTime = new Date().valueOf();
      console.log(orderEntity);
      let _this = this;
      this.$http.put("/orders/state", orderEntity).then(function (response) {
        _this.$message({
          message: "完成订单！",
          type: "success",
        });
        //将订单加到已完成队列
        const index = _this.orderAccepted.findIndex(
          (option) => option.id === orderEntity.id
        );
        //转换时间的格式
        orderDtoEntity.orderFinishTime = _this.getDate(orderDtoEntity.orderFinishTime);
        _this.orderAccepted.splice(index, 1);
        _this.orderFinished.push(orderEntity);
      });
    },
    calculateTotalPrice(foodEntity) {
      console.log(foodEntity);
      return (foodEntity.foodPrice * 10 * foodEntity.foodNumber) / 10; // 计算总价
    },
    calculateOrderPrice(orderEntity) {
      let _this = this;
      let totalPrice = 0;
      for (let i = 0; i < orderEntity.foodJudgementList.length; i++) {
        totalPrice +=
          orderEntity.foodJudgementList[i].food.price *
          orderEntity.foodJudgementList[i].foodNumber;
      }
      return totalPrice;
    },
    // 更新分页控件的显示数据
    updatePagination(pagination, data) {
      pagination.currentPage = data.current;
      pagination.pageSize = data.size;
      pagination.totalCount = parseInt(data.total);
    },
    // 改变分页的每页的页数
    handleSizeChange(size) {
      this.getOrderPagination(this.pagintion.currentPage, size);
    },
    // 改变分页的当前页面
    handleCurrentChange(currentPage) {
      this.getOrderPagination(currentPage, this.pagination.pageSize);
    },
  },
};
</script>

<style>
.order-header {
  margin-top: 30px;
  position: relative;
}
.order-column-card {
  border-radius: 15px !important;
  height: 580px;
}
.order-card {
  width: 1050px;
  margin: 0px auto 10px;
}
.order-card:hover {
  transform: translateY(-3px);
  box-shadow: 3px 3px 3px 3px rgba(0, 0, 0, 0.3) !important;
  cursor: pointer;
}
.order-image {
  float: left;
  margin: 0px 10px 10px;
  width: 50px;
  height: 40px;
}
.order-time {
  float: left;
  /* font-size: 20px; */
  margin: 10px;
  text-align: left;
}
.order-comment {
  font-size: 14px;
  width: 600px;
  overflow: hidden; /* 超出部分隐藏 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* 设置显示的行数 */
  text-indent: 30px; /* 设置首行缩进为 20 像素 */
  margin-bottom: 20px;
}
.order-rate-div {
  float: right;
  /* margin: 10px; */
}
.order-food-title {
  float: left;
  text-align: left;
  margin: 0px;
  width: 60%;
}
.order-food-price {
  float: right;
  margin: 0px 0px;
  width: 100px;
  text-align: left;
}
.order-o-operation-div {
  float: right;
  margin: 0px 20px 10px;
}
</style>
